let express = require('express');
let router = express.Router();

const checkJWTMiddleWare = require('../middleWare/checkJWTMiddleWare');

// 此路由需要登录后才能访问
router.use(checkJWTMiddleWare);

// 实体类
const Response = require('../entity/http/Response');
const Plan = require('../entity/plan/Plan');
const ObjId = require('../entity/common/ObjId');

// 业务层
const planService = require('../service/planService');

/*
 * 获取计划列表
 */
router.get('/getPlanList', async function(req, res, next) {
    let { uid } = req.jwtResult.data;
    planService.getPlanList(uid).then((result) => {
        res.status(result.success ? 200 : 400).json(result);
    }).catch((err) => {
        res.status(500).json((new Response()).fail("获取计划列表失败"));
    });
});

/*
 * 添加计划
 * 打卡次数的取值范围还没做
 */
router.post('/addPlan', async function(req, res, next) {
    // 读取请求参数
    let { uid } = req.jwtResult.data;
    let plan = new Plan(req);
    // 判断参数是否合法
    let flag = plan.check();
    if (!flag.success) {
        return res.status(400).json(flag);
    }
    // 调用业务层
    planService.addPlan(uid, plan).then((result) => {
        res.status(result.success ? 200 : 400).json(result);
    }).catch((err) => {
        res.status(500).json((new Response()).fail("添加计划失败"));
    });
});

/*
 * 删除计划
 */
router.post('/deletePlan', async function(req, res, next) {
    // 读取请求参数
    let { uid } = req.jwtResult.data;
    let plan = new ObjId(req.body, 'planId');
    // 判断参数是否合法
    let flag = plan.check();
    if (!flag.success) {
        return res.status(400).json(flag);
    }
    // 调用业务层
    planService.deletePlan(uid, plan.id).then((result) => {
        res.status(result.success ? 200 : 400).json(result);
    }).catch((err) => {
        res.status(500).json((new Response()).fail("删除计划失败"));
    });
});

/*
 * 查看计划
 */
router.get('/getPlanInfo', async function(req, res, next) {
    let plan = new ObjId(req.query, 'id');
    let flag = plan.check();
    if (!flag.success) {
        return res.status(400).json(flag);
    }
    planService.getPlanInfo(req.jwtResult.data.uid, plan.id).then((result) => {
        res.status(result.success ? 200 : 400).json(result);
    }).catch((err) => {
        res.status(500).json((new Response()).fail("获取计划列表失败"));
    });
});

/*
 * 打卡该计划
 */
router.post('/checkinPlan', async function(req, res, next) {
    let { uid } = req.jwtResult.data;
    let plan = new ObjId(req.body, 'planId');
    let flag = plan.check();
    if (!flag.success) {
        return res.status(400).json(flag);
    }
    planService.checkinPlan(uid, plan.id, req.formatDate).then((result) => {
        res.status(result.success ? 200 : 400).json(result);
    }).catch((err) => {
        res.status(500).json((new Response()).fail("打卡计划失败"));
    });
});

module.exports = router;